#include "ItemBank.h"
#include <string>
#include "pugixml.hpp"
#include "GameConfig.h"
#include "Config.h"
#include "ItemFactory.h"

using namespace std;
using namespace pugi;

ItemBank::ItemBank(void)
{
	_listItemFactory = NULL;
}


ItemBank::~ItemBank(void)
{
	CC_SAFE_RELEASE(_listItemFactory);
}

ItemBank* ItemBank::sharedItemBank()
{
	if (!_instance)
		_instance = new ItemBank();
	return _instance;
}

void ItemBank::initBank()
{
	setItemFactories(CCDictionary::create());
	// Do anything
	std:string data = string(dynamic_cast<CCString*>(GameConfig::sharedGameConfig()->getConfigData()->objectForKey(CONFIG_ITEMS))->getCString());

	xml_document doc;
	xml_parse_result result = doc.load(data.c_str());
	CCAssert(result.status == status_ok, "FAILD");

	xml_node node = doc.child("Root").child("Items");
	for (xml_node i = node.child("Item"); i; i = i.next_sibling("Item"))
	{
		ItemFactory* eFactory = ItemFactory::create();
		eFactory->parseXml(i);
		_listItemFactory->setObject(eFactory, eFactory->getId()->getCString());
	}
}

void ItemBank::clearBank()
{
	delete _instance;
	_instance = NULL;
}

ItemFactory* ItemBank::getItemFactory( char* type )
{
	return dynamic_cast<ItemFactory*>(_listItemFactory->objectForKey(type));
}

ItemBank* ItemBank::_instance = NULL;
